package com.heima.common.advice;

import io.seata.core.context.RootContext;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.transaction.TransactionException;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

/**
 * 用来处理程序调用异常，由于被全局异常处理后，导致分布式事务失效
 *
 * @author: itheima
 * @create: 2022-05-16 08:42
 */
@Slf4j
@Aspect
@Component
@ConditionalOnClass(RootContext.class)
public class ExceptionTransactionRollback {

    /**
     * 切面：将增强作用到切入点
     * pointcut 切入点 对业务层进行增强
     *
     * @param e
     */
    @AfterThrowing(throwing = "e", pointcut = "execution(* com.heima.*.service.*.*(..))")
    public void rollback(Throwable e) throws TransactionException, io.seata.core.exception.TransactionException {
        log.error("分之事务执行异常，进行全局事务回滚,{}", e.getMessage());
        //判断当前业务方法是否加入到全局事务中（是否为分布式事务管理）
        String xid = RootContext.getXID();
        if (StringUtils.isNotBlank(xid)) {
            GlobalTransactionContext.reload(xid).rollback();
        }
    }

}
